package com.ingrun.tuboshu.utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.ingrun.tuboshu.entity.SysLogLogin;
import com.ingrun.tuboshu.service.ISysLogLoginService;
import com.ingrun.tuboshu.utils.ip.AddressUtils;
import com.ingrun.tuboshu.utils.ip.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 *
 * @author ruoyi
 */
public class AsyncFactory {
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @return 任务task
     */
    public static TimerTask recordLogLogin(String userId, final String username, final String status, final String message, String userType, String requestId) {
        final UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(AsyncFactory.getBlock(ip));
                s.append(address);
                s.append(AsyncFactory.getBlock(username));
                s.append(AsyncFactory.getBlock(status));
                s.append(AsyncFactory.getBlock(message));
                s.append(AsyncFactory.getBlock(userType));

                // 打印信息到日志
                sys_user_logger.info(s.toString());
                // 获取客户端操作系统
                String os = userAgent.getOs().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();

                // 封装对象
                SysLogLogin sysLogLogin = new SysLogLogin();
                sysLogLogin.setUserId(userId);
                sysLogLogin.setUserName(username);
                sysLogLogin.setIpAddress(ip);
                sysLogLogin.setIpLocation(address);
                sysLogLogin.setBrowser(browser);
                sysLogLogin.setOs(os);
                sysLogLogin.setStatus(status);
                sysLogLogin.setMessage(message);
                sysLogLogin.setLoginTime(DateUtil.date());
                sysLogLogin.setUserType(userType);
                sysLogLogin.setCreateBy(username);
                sysLogLogin.setRequestId(requestId);

                // 插入数据
                SpringContextKit.getBean(ISysLogLoginService.class).save(sysLogLogin);
            }
        };
    }

    private static String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg.toString().trim() + "]";
    }

}
